import React, { useContext, useEffect, useState,useRef } from 'react'
import './Shop.less'
import Header from '../../components/Header/Header'
import { reqcartlist, reqcartdelete, reqcartedit } from '../../http/api'
import { SwipeAction, Stepper, Dialog, Toast } from 'antd-mobile'
import yImg from '../../assets/img/y.jpeg'
import nImg from '../../assets/img/n.jpeg'
import { $pre } from '../../http/http'
import { Link } from 'react-router-dom'
import { MyContext } from '../../App'
import {filterPrice} from '../../filters/index'
export default function Shop(props) {
  let { state: { userInfo: { uid } } } = useContext(MyContext);
  let [list, setList] = useState([]);
  let [allChecked, setAllChecked] = useState(false);
  let isEdit = useRef();
  let couponInfo = props.location.state?.couponInfo ? props.location.state?.couponInfo : {};
  //获取列表
  let getList = async () => {
    let { data: res } = await reqcartlist({ uid });
    if (res.code === 200) {
      let arr0 = res.list[0].content ? res.list[0].content : [];
      let arr1 = res.list[1].content ? res.list[1].content : [];
      let arr = [...arr0, ...arr1];
      arr.forEach((item) => {
        let obj = list.find(i => i.id == item.id);
        obj ? item.isChecked = obj.isChecked : item.isChecked = false;
      })
      setAllChecked(arr.length > 0 ? arr.every(item => item.isChecked) : false)
      setList(arr);
    }
  }
  //购物车删除
  let delCart = async (id) => {
    let { data: res } = await reqcartdelete({ id });
    if (res.code === 200) {
      Toast.show({ content: res.msg });
      getList();
    }
  }
  //购物车修改
  let editCart = async (v, id) => {
    if (isEdit.current) {
      isEdit.current = false;
      // console.log(isEdit);
      let { num } = list.find(item => item.id == id);
      let res;
      if (v > num) {
        //加
        res = await reqcartedit({ id, type: 2 });
      } else {
        //减
        res = await reqcartedit({ id, type: 1 });
      }
      if (res.data.code === 200) {
        getList();
      }
    }
  }
  //单选
  let changeOne = (id)=>{
    let arr =list;
    let index = arr.findIndex(item=>item.id === id);
    arr[index].isChecked = !arr[index].isChecked;
    setList([...arr]);
    setAllChecked(arr.every(item=>item.isChecked))
  }
  //全选
  let changeAll =()=>{
    let flag = allChecked
    setAllChecked(!flag);
    list.forEach(item=> item.isChecked = !flag);
    setList([...list]);
  }
  //总价
  let totalPrice = list.reduce((a,b)=>{
      return b.isChecked ? a+b.num*b.price : a;
  },0)
  useEffect(() => {
    isEdit.current=true;
    getList();
  }, [])
  useEffect(()=>{
    isEdit.current=true;
  },[list])
  return (
    <div className='shop'>
      <Header title='购物车' back></Header>
      <div className="list">
        {list.length > 0 ? (list.map(item => (<SwipeAction
          key={item.id}
          rightActions={[
            {
              key: 'delete',
              text: '删除',
              color: 'danger',
              onClick: async () => {
                let result = await Dialog.confirm({
                  content: '确定要删除吗？',
                });
                if (result) {
                  delCart(item.id);
                }
              },
            },
          ]}
        >
          <div className="item">
            <img
              onClick={()=>changeOne(item.id)}
              src={item.isChecked ? yImg : nImg}
              className="checkbox"
              alt=""
            />
            <img
              className="img"
              src={$pre + item.img}
              alt=""
            />
            <div className="right">
              <h3>商品名称:{item.goodsname}</h3>
              <div>单价:{item.price}</div>
              <div>数量：x {item.num}</div>
              <div>
                <Stepper onChange={(v) => editCart(v, item.id)} inputReadOnly value={item.num} min={1} />
              </div>
            </div>
          </div>
        </SwipeAction>))) : (<div>暂无数据</div>)}

      </div>
      <div className="footer">
        <div className="allChecked" onClick={() => changeAll() }>
          <img className="checkbox" src={allChecked ? yImg : nImg} alt="" />
          全选
        </div>
        <div className='couponBox'>
          <Link to={'/coupon'}>优惠券</Link>
          {couponInfo.title ? (<span>-{couponInfo.money}</span>) : (null)}
        </div>
        <div className="allPrice">￥{totalPrice === 0 ? filterPrice(totalPrice)  : (filterPrice(totalPrice) - (couponInfo.money || 0))}</div>
      </div>
    </div>
  )
}
